const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();


/**
 * 获取所有供应商
 */
exports.getAllSuppliers = async (req, res) => {
  try {
    // 不过滤状态，获取所有供应商
    console.log("获取所有供应商，包括停用的");
    const suppliers = await prisma.supplier.findMany({
      orderBy: {
        name: 'asc'
      }
    });
    
    console.log("返回的供应商数据:", suppliers);
    
    return res.status(200).json({
      success: true,
      data: suppliers
    });
  } catch (error) {
    console.error('获取供应商列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取供应商列表失败',
      error: error.message
    });
  }
};

/**
 * 获取单个供应商详情
 */
exports.getSupplierById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const supplier = await prisma.supplier.findUnique({
      where: { id: Number(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    return res.status(200).json({
      success: true,
      data: supplier
    });
  } catch (error) {
    console.error('获取供应商详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取供应商详情失败',
      error: error.message
    });
  }
};

/**
 * 创建供应商
 */
exports.createSupplier = async (req, res) => {
  try {
    const { name, contactPerson, phone, email, address, status, remarks } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '供应商名称不能为空'
      });
    }
    
    const existingSupplier = await prisma.supplier.findFirst({
      where: { name }
    });
    
    if (existingSupplier) {
      return res.status(400).json({
        success: false,
        message: '供应商名称已存在'
      });
    }
    
    const supplier = await prisma.supplier.create({
      data: {
        name,
        contactPerson,
        phone,
        email,
        address,
        status: status !== undefined ? Boolean(status) : true,
        remarks
      }
    });
    
    // 记录审计日志
    await logAudit({
      userId: req.user.id,
      action: 'create',
      module: 'supplier',
      description: `创建供应商 "${name}"`,
      details: JSON.stringify(supplier)
    });
    
    return res.status(201).json({
      success: true,
      data: supplier,
      message: '供应商创建成功'
    });
  } catch (error) {
    console.error('创建供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '创建供应商失败',
      error: error.message
    });
  }
};

/**
 * 更新供应商
 */
exports.updateSupplier = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, contactPerson, phone, email, address, status, remarks } = req.body;
    
    const supplier = await prisma.supplier.findUnique({
      where: { id: Number(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    if (name && name !== supplier.name) {
      const existingSupplier = await prisma.supplier.findFirst({
        where: {
          name,
          id: {
            not: Number(id)
          }
        }
      });
      
      if (existingSupplier) {
        return res.status(400).json({
          success: false,
          message: '供应商名称已存在'
        });
      }
    }
    
    const updatedSupplier = await prisma.supplier.update({
      where: { id: Number(id) },
      data: {
        name: name || supplier.name,
        contactPerson: contactPerson !== undefined ? contactPerson : supplier.contactPerson,
        phone: phone !== undefined ? phone : supplier.phone,
        email: email !== undefined ? email : supplier.email,
        address: address !== undefined ? address : supplier.address,
        status: status !== undefined ? Boolean(status) : supplier.status,
        remarks: remarks !== undefined ? remarks : supplier.remarks
      }
    });
    
    // 记录审计日志
    await logAudit({
      userId: req.user.id,
      action: 'update',
      module: 'supplier',
      description: `更新供应商 "${updatedSupplier.name}"`,
      details: JSON.stringify({
        before: supplier,
        after: updatedSupplier
      })
    });
    
    return res.status(200).json({
      success: true,
      data: updatedSupplier,
      message: '供应商更新成功'
    });
  } catch (error) {
    console.error('更新供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '更新供应商失败',
      error: error.message
    });
  }
};

/**
 * 删除供应商
 */
exports.deleteSupplier = async (req, res) => {
  try {
    const { id } = req.params;
    
    const supplier = await prisma.supplier.findUnique({
      where: { id: Number(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    // 检查供应商是否有关联的入库单
    const stockInCount = await prisma.stockInOrder.count({
      where: { supplierId: Number(id) }
    });
    
    if (stockInCount > 0) {
      return res.status(400).json({
        success: false,
        message: '供应商已有入库单记录，无法删除'
      });
    }
    
    // 如果没有关联记录，可以删除供应商
    await prisma.supplier.delete({
      where: { id: Number(id) }
    });
    

    
    return res.status(200).json({
      success: true,
      message: '供应商删除成功'
    });
  } catch (error) {
    console.error('删除供应商失败:', error);
    return res.status(500).json({
      success: false,
      message: '删除供应商失败',
      error: error.message
    });
  }
};

/**
 * 获取供应商的入库记录
 */
exports.getSupplierStockInOrders = async (req, res) => {
  try {
    const { id } = req.params;
    
    const supplier = await prisma.supplier.findUnique({
      where: { id: Number(id) }
    });
    
    if (!supplier) {
      return res.status(404).json({
        success: false,
        message: '供应商不存在'
      });
    }
    
    const stockInOrders = await prisma.stockInOrder.findMany({
      where: { supplierId: Number(id) },
      include: {
        warehouse: {
          select: {
            id: true,
            name: true
          }
        },
        operator: {
          select: {
            id: true,
            name: true,
            username: true
          }
        }
      },
      orderBy: {
        orderDate: 'desc'
      }
    });
    
    return res.status(200).json({
      success: true,
      data: stockInOrders
    });
  } catch (error) {
    console.error('获取供应商入库记录失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取供应商入库记录失败',
      error: error.message
    });
  }
}; 